package com.epam.qanda.web.servlet.logged;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.UserService;

public class UploadImgServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String STD_AVATAR = "std_avatar.png";
	private Random rand = new Random();
	private static final Logger LOG = Logger.getLogger("stdout");

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.sendRedirect(request.getHeader("referer"));
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart) {
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();

		factory.setSizeThreshold(1024 * 1024);

		File tempDir = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(tempDir);

		ServletFileUpload upload = new ServletFileUpload(factory);

		upload.setSizeMax(1024 * 1024 * 10);
		upload.setHeaderEncoding("UTF-8");
		List<String> fieldNames = new ArrayList<String>();
		List<String> fieldValues = new ArrayList<String>();
		try {
			List<?> items = upload.parseRequest(request);
			Iterator<?> iter = items.iterator();

			while (iter.hasNext()) {
				FileItem item = (FileItem) iter.next();
				if (item.isFormField()) {
					processFormField(item, fieldNames, fieldValues);
				} else {
					processUploadedFile(item, fieldNames, fieldValues);
				}
			}
		} catch (Exception e) {
			LOG.warn(e.getMessage());
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}
		User user = (User) request.getSession().getAttribute("user");
		user.setPhoto(fieldValues.get(fieldNames.indexOf("inputImg")));
		new UserService().update(user);
		response.sendRedirect(request.getHeader("referer"));
	}

	private void processUploadedFile(FileItem item, List<String> names, List<String> values)
			throws Exception {
		File uploadedFile = null;
		String path = null;
		String itemName = item.getName();
		if (itemName != null && !itemName.isEmpty()) {
			do {
				path = "resources" + File.separator + "images" + File.separator + "avatar"
						+ File.separator + rand.nextInt(100) + itemName;
				uploadedFile = new File(getServletContext().getRealPath("") + File.separator + path);
			} while (uploadedFile.exists());
		} else {
			names.add("inputImg");
			values.add("resources" + File.separator + "images" + File.separator + "avatar"
					+ File.separator + STD_AVATAR);
			return;
		}
		uploadedFile.createNewFile();
		item.write(uploadedFile);
		names.add("inputImg");
		values.add(path);
	}

	private void processFormField(FileItem item, List<String> names, List<String> values) {
		names.add(item.getFieldName());
		try {
			values.add(new String(item.getString().getBytes("ISO-8859-1"), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			LOG.warn(e.getMessage());
		}
	}
}
